package com.margo.project.transaction.simple.action;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.margo.project.transaction.simple.service.JdbcTemplateTraService;
import com.margo.project.transaction.throwable.MargoRollbackThrowable;

@RequestMapping("/transaction")
@Controller
public class MargoTransactionController {
	
	private Logger logger=LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private JdbcTemplateTraService jdbcTemplateTraService;
	
	/**
	 * http://localhost:8080/transaction/rollback
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/rollback")
	public int rollback() {
		try {
			jdbcTemplateTraService.rollback();
		} catch (MargoRollbackThrowable e) {
			logger.info(e.getMessage(),e);
		}
		return 1;
	}
	
	/**
	 * http://localhost:8080/transaction/commit
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/commit")
	public int commit(HttpServletRequest request) {
		log(request);
		try {
			jdbcTemplateTraService.commit();
		} catch (MargoRollbackThrowable e) {
			logger.info(e.getMessage(),e);
		}
		return 1;
	}
	
	/**
	 * http://localhost:8080/transaction/listener
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/listener")
	public int listener(HttpServletRequest request) {
		log(request);
		jdbcTemplateTraService.listener();
		return 1;
	}
	
	private void log(HttpServletRequest request) {
		logger.info("ContextPath:"+request.getContextPath());
		logger.info("ServletPath:"+request.getServletPath());
		logger.info("RequestURI:"+request.getRequestURI());
		logger.info("RequestURL:"+request.getRequestURL().toString());
	}
}
